package com.feng.dt.controller;

import com.feng.common.exception.ValidationException;
import com.feng.common.web.WebCommonResponse;
import com.feng.common.web.WebCommonResponseBuilder;
import com.feng.profile.service.ProfileUserService;
import com.feng.profile.vo.LoginVo;
import com.feng.profile.vo.UserAddReq;
import com.feng.profile.vo.UserInfo;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Lee
 */
@RequestMapping("/sys/user")
@RestController
public class SysUserController {

    private final static Logger LOGGER = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private ProfileUserService profileUserService;

    @Autowired
    private Producer producer;

    @PostMapping("/addUser.do")
    public WebCommonResponse<Void> addUser(@RequestBody @Valid UserAddReq userAddReq){
        try {
            profileUserService.addSysUser(userAddReq);
        } catch (ValidationException e) {
            return new WebCommonResponseBuilder<Void>()
                    .fail(Objects.isNull(e.getErrorCode()) ? WebCommonResponse.CODE_UN_KNOW_FAIL : e.getErrorCode().toString(), e.getMessage())
                    .build();
        }
        return new WebCommonResponseBuilder<Void>().success().build();
    }

    @PostMapping("/login.do")
    public WebCommonResponse<UserInfo> login(@RequestBody @Valid LoginVo loginVo){
        UserInfo userInfo = null;
        try {
            userInfo = profileUserService.login(loginVo);
        } catch (ValidationException e) {
            return new WebCommonResponseBuilder<UserInfo>()
                    .fail(Objects.isNull(e.getErrorCode()) ? WebCommonResponse.CODE_UN_KNOW_FAIL : e.getErrorCode().toString(), e.getMessage())
                    .build();
        }
        return new WebCommonResponseBuilder<UserInfo>().success().build(userInfo);
    }

    @GetMapping("/captcha.do")
    public void captcha(HttpServletResponse response) throws IOException {
        // 不缓存
        response.setHeader("Cache-Control","no-store,no-cache");
        // 相应格式
        response.setContentType("image/jpeg");
        // 生成文字
        String imageText = producer.createText();
        // 生成图片
        BufferedImage image = producer.createImage(imageText);
        // 我是用的是shiro
        Session session = SecurityUtils.getSubject().getSession();
        session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY,imageText);


        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpeg",outputStream);
        outputStream.flush();
        LOGGER.info(session.getId() + " : " + imageText);
    }


}
